
// packageE/receptionHall/index.js
const util = require("../../../utils/util.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 筛选类型
        filterType: 'nearby',
        // 订单数据
        // orders: [],
        orders: [
            {
                orderId: '1001',
                createTime: '2023-09-18 10:30',
                status: 1,
                statusText: '待付款',
                flavor: '草莓味',
                clientPhone: "13813357897",
                detailAddress: "图书城公寓文创楼2号",
                spec: '500g/瓶',
                imageUrl: 'https://xxx.xjdio.com/static/img/1.jpg',//'https://picsum.photos/200/200?random=1',
                count: 2,
                distance: 23.86,
                latitude: 31.338399, // 替换为实际纬度
                longitude: 120.595502, // 替换为实际经度
                status: 'pending',
                totalPrice: 56.00
            },
            {
                orderId: '1002',
                createTime: '2023-09-17 15:20',
                status: 2,
                statusText: '制作中',
                flavor: '红枣味',
                clientPhone: "13813357897",
                latitude: 31.338399, // 替换为实际纬度
                longitude: 120.595502, // 替换为实际经度
                detailAddress: "图书城公寓文创楼2号",
                spec: '500g/瓶',
                imageUrl: 'https://xxx.xjdio.com/static/img/1.jpg',//'https://picsum.photos/200/200?random=2',
                count: 1,
                totalPrice: 28.00,
                distance: 23.86,
            },
            {
                orderId: '1003',
                createTime: '2023-09-16 09:15',
                status: 'completed',
                statusText: '配送中',
                clientPhone: "13813357897",
                latitude: 31.338399, // 替换为实际纬度
                longitude: 120.595502, // 替换为实际经度
                detailAddress: "图书城公寓文创楼2号",
                flavor: '蓝莓味',
                spec: '500g/瓶',
                imageUrl: 'https://xxx.xjdio.com/static/img/1.jpg',//'https://picsum.photos/200/200?random=3',
                count: 3,
                totalPrice: 84.00
            },
            {
                orderId: '1004',
                createTime: '2023-09-15 14:00',
                status: 'pending',
                statusText: '已完成',
                flavor: '芒果味',
                clientPhone: "13813357897",
                latitude: 31.338399, // 替换为实际纬度
                longitude: 120.595502, // 替换为实际经度
                detailAddress: "图书城公寓文创楼2号",
                spec: '500g/瓶',
                imageUrl: 'https://xxx.xjdio.com/static/img/1.jpg',//'https://picsum.photos/200/200?random=4',
                count: 2,
                totalPrice: 56.00,
                distance: 23.86,
            },
            {
                orderId: '1005',
                createTime: '2023-09-14 11:45',
                status: 'taken',
                statusText: '已完成',
                flavor: '蜜桃味',
                clientPhone: "13813357897",
                latitude: 31.338399, // 替换为实际纬度
                longitude: 120.595502, // 替换为实际经度
                detailAddress: "图书城公寓文创楼2号",
                spec: '500g/瓶',
                imageUrl: 'https://xxx.xjdio.com/static/img/1.jpg',//'https://picsum.photos/200/200?random=5',
                count: 1,
                totalPrice: 28.00,
                distance: 23.86,
            }
        ],
        // 分页信息
        page: 1,
        pageSize: 10,
        isLoading: false,
        noMore: false,
        // 地图预览相关
        showMapModal: false,
        currentOrder: null,
        markers: [],
        // 打卡相关数据
        showCheckinModal: false,
        checkinPhoto: '',
        currentOrderId: null

    },
    

    GetServiceOrdersinfo(param1, param2, param3) {
        return wx.Http.get("/ServiceOrderAPPService/GetServiceOrders", {
            PageIndex: param1,
            PageCount: param2,
            Status: param3

        });
    },
    Deletefile(param1) {
        return wx.Http.post("/AccountAppService/Deletefile", {
            DeletePic: param1,

        });
    },
    GetNearByServiceOrders(param1, param2, param3, param4) {
        return wx.Http.post("/ServiceOrderAPPService/GetNearByServiceOrders", {
            PageIndex: param1,
            PageCount: param2,
            Status: param3,
            accountid: param4
        });
    },
    CheckinServiceOrder(param1, param2, param3) {
        return wx.Http.post("/ServiceOrderAPPService/CheckinServiceOrder", {
            id: param1,
            CheckinPhoto: param2,
            Status: param3
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 获取用户位置
        // this.getUserLocation();
        // 加载订单数据
        // this.loadOrders('nearby');
    },
    // 获取用户位置
    getUserLocation() {
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            success(res) {
                that.setData({
                    userLatitude: res.latitude,
                    userLongitude: res.longitude
                });
            },
            fail() {
                wx.showToast({
                    title: '获取位置失败',
                    icon: 'none'
                });
            }
        });
    },

    // 加载订单数据
    loadOrders(type) {
        if (this.data.isLoading || this.data.noMore) return;
        this.setData({ isLoading: true });
        if (type == 'all') {
            this.GetServiceOrdersinfo(this.data.page, this.data.pageSize, "").then((res) => {
                console.log(res.data)
                const newOrders = res.data.list;
                this.setData({
                    orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
                    isLoading: false,
                    noMore: newOrders.length < this.data.pageSize
                });
            })
        } else if (type == 'nearby') {
            this.GetNearByServiceOrders(this.data.page, this.data.pageSize, "pending", 0).then((res) => {
                console.log(res.data)
                const newOrders = res.data.value.result;
                this.setData({
                    orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
                    isLoading: false,
                    noMore: newOrders.length < this.data.pageSize
                });
            })
        } else if (type == 'taken') {
            this.GetNearByServiceOrders(this.data.page, this.data.pageSize, "taken", 1).then((res) => {
                console.log(res.data)
                const newOrders = res.data.value.result;
                this.setData({
                    orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
                    isLoading: false,
                    noMore: newOrders.length < this.data.pageSize
                });
            })
        } else if (type == 'completed') {
            this.GetNearByServiceOrders(this.data.page, this.data.pageSize, "completed", 1).then((res) => {
                console.log(res.data)
                const newOrders = res.data.value.result;
                this.setData({
                    orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
                    isLoading: false,
                    noMore: newOrders.length < this.data.pageSize
                });
            })
        }


        // 模拟API请求
        // setTimeout(() => {
        // }, 1000);
    },

    // 生成模拟订单数据
    generateOrders() {
        const services = ['日常保洁', '深度清洁', '家电清洗', '新居开荒', '保姆服务', '月嫂服务'];
        const statuses = ['pending', 'taken'];
        const orders = [];

        for (let i = 0; i < this.data.pageSize; i++) {
            const serviceType = services[Math.floor(Math.random() * services.length)];
            const status = statuses[Math.floor(Math.random() * statuses.length)];

            orders.push({
                id: this.data.page * 100 + i,
                serviceType,
                price: (50 + Math.floor(Math.random() * 200)).toFixed(2),
                serviceDate: `2023-${this.padNum(6 + this.data.page)}-${this.padNum(15 + i)}`,
                serviceTime: `${this.padNum(9 + i % 6)}:00-${this.padNum(11 + i % 6)}:00`,
                clientName: `客户${this.data.page * 10 + i}`,
                clientPhone: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
                remark: i % 3 === 0 ? '需要带清洁工具，家里有宠物' : '',
                distance: (0.5 + Math.random() * 5).toFixed(1),
                status,
                address: '北京市朝阳区建国门外大街1号国贸大厦',
                latitude: 39.90923 + (Math.random() - 0.5) * 0.02,
                longitude: 116.397428 + (Math.random() - 0.5) * 0.02
            });
        }

        return orders;
    },

    // 补零函数
    padNum(num) {
        return num < 10 ? `0${num}` : num;
    },

    // 改变筛选类型
    changeFilter(e) {
        const type = e.currentTarget.dataset.type;
        this.setData({
            filterType: type,
            page: 1,
            // orders: [],
            noMore: false
        }, () => {
            // this.loadOrders(type);
        });
    },

    // 下拉刷新
    onRefresh() {
        this.setData({
            page: 1,
            orders: [],
            noMore: false
        }, () => {
            this.loadOrders(this.data.filterType);
            wx.stopPullDownRefresh();
        });
    },

    // 上拉加载更多
    onReachBottom() {
        if (!this.data.noMore) {
            this.setData({ page: this.data.page + 1 }, () => {
                this.loadOrders(this.data.filterType);
            });
        }
    },
    grabOrder1(e) {
        wx.showModal({
            title: '提示',
            content: '是否确认接单？',
            complete: (res) => {
                if (res.cancel) {
                    wx.showToast({
                        title: '已取消',
                        icon: 'success',
                        duration: 600
                    });
                }

                if (res.confirm) {
                    wx.showToast({
                        title: '抢单成功',
                        icon: 'success',
                        duration: 600
                    });
                }
            }
        })
    },
    // 一键抢单
    grabOrder(e) {
        const _this = this;
        const orderId = e.currentTarget.dataset.id;
        const orderIndex = this.data.orders.findIndex(o => o.id === orderId);

        // 防止重复点击
        if (this.data.orders[orderIndex].status !== 'pending') return;

        // 更新订单状态为处理中
        this.setData({
            [`orders[${orderIndex}].status`]: 'processing'
        });

        this.tokenP().then((res) => {
            if (!res.data) {
                wx.navigateTo({
                    url: '/pages/user/login/index',
                })
            } else {
                this.GetmyTalentPool().then((resTalentPoolInfo) => {
                    if (resTalentPoolInfo.data) {
                        wx.Http.post("/ServiceOrderAPPService/TakenServiceOrder", {
                            Status: 'taken',
                            Id: item.id,
                            CaregiverId: resTalentPoolInfo.data.accountId,
                            CaregiverNickname: resTalentPoolInfo.data.name,
                            AuntPhone: resTalentPoolInfo.data.telephone,
                        }).then((res) => {
                            if (res.data) {
                                _this.setData({
                                    noMore: false
                                }, () => {

                                    _this.GetIntegralpiceinfos("接单").then((res) => {
                                        var myjiangli = res.data;

                                        _this.setMonkey(res.data, 0, "抢单扣积分").then((res) => {
                                            if (res.data) {
                                                _this.setData({
                                                    noMore: false
                                                }, () => {
                                                    _this.loadOrders(_this.data.filterType);
                                                    wx.showToast({
                                                        title: '抢单成功',
                                                        icon: 'success',
                                                        duration: 600
                                                    });
                                                    wx.showToast({
                                                        title: '扣积分' + myjiangli + "个",
                                                        duration: 2000
                                                    })
                                                })

                                            }
                                        })
                                    })

                                })
                            }

                        })

                    } else {
                        wx.showModal({
                            title: '提示',
                            content: '填写简历',
                            complete: (res) => {
                                if (res.cancel) {

                                }

                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/pages/Talent/rcjl/index',
                                    })
                                }
                            }
                        })


                    }
                })



            }
        })


        // // 模拟API请求
        // setTimeout(() => {
        //     // 震动反馈
        //     wx.vibrateShort();

        //     // 更新订单状态
        //     this.setData({
        //         [`orders[${orderIndex}].status`]: 'taken'
        //     });

        //     wx.showToast({
        //         title: '抢单成功',
        //         icon: 'success',
        //         duration: 2000
        //     });
        // }, 1000);
    },
    tokenP() {
        return wx.Http.post('/AccountAppService/CheckmyUserPhone', {})
    },
    GetmyTalentPool() {
        return wx.Http.post('/TalentPoolAppService/GetmyTalentPool')
    },
    setMonkey(monkey, RewardCoinId, Title) {
        return wx.Http.post("/AccountAppService/UpdatemysysUserinfos", {
            integral: -monkey,
            rewardCoinId: RewardCoinId,
            title: Title,
        });
    },
    //获取积分多少
    GetIntegralpiceinfos(text) {
        return wx.Http.post("/IntegralAppService/GetIntegralpice", { type: text });
    },
    async grabOrder(e) {
        var id = e.currentTarget.dataset.id;
        const _this = this;
        debugger
        let res = await this.tokenP();

        if (!res.data) {
            wx.navigateTo({
                url: '/pages/user/login/index',
            })
        } else {
            var resTalentPoolInfo = await this.GetmyTalentPool();

            if (resTalentPoolInfo.data) {
                wx.Http.post("/ServiceOrderAPPService/TakenServiceOrder", {
                    Status: 'taken',
                    Id: id,
                    CaregiverId: resTalentPoolInfo.data.accountId,
                    CaregiverNickname: resTalentPoolInfo.data.name,
                    AuntPhone: resTalentPoolInfo.data.telephone,
                }).then((res) => {
                    if (res.data) {
                        _this.setData({
                            noMore: false
                        }, () => {

                            _this.GetIntegralpiceinfos("接单").then((res) => {
                                var myjiangli = res.data;

                                _this.setMonkey(res.data, 0, "抢单扣积分").then((res) => {
                                    if (res.data) {
                                        _this.setData({
                                            noMore: false
                                        }, () => {
                                            _this.loadOrders(_this.data.filterType);
                                            wx.showToast({
                                                title: '抢单成功',

                                            })
                                            wx.showToast({
                                                title: '扣' + myjiangli + "个积分",
                                                duration: 2000
                                            })
                                        })

                                    }
                                })
                            })

                        })
                    }

                })

            } else {
                wx.showModal({
                    title: '提示',
                    content: '填写简历',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {
                            wx.navigateTo({
                                url: '/pages/Talent/rcjl/index',
                            })
                        }
                    }
                })


            }

        }

    },
    // 查看客户位置
    viewLocation(e) {
        const orderId = e.currentTarget.dataset.id;
        const order = this.data.orders.find(o => o.id === orderId);

        if (order) {
            this.setData({
                showMapModal: true,
                currentOrder: order,
                markers: [{
                    id: 0,
                    latitude: order.latitude,
                    longitude: order.longitude,
                    iconPath: '/images/navigation.png',
                    width: 30,
                    height: 30,
                    callout: {
                        content: order.address,
                        color: '#1890ff',
                        borderRadius: 10,
                        padding: 5,
                        display: 'ALWAYS'
                    }
                }]
            });
        }
    },

    // 关闭地图模态框
    closeMapModal() {
        this.setData({ showMapModal: false });
    },

    // 导航前往
    openLocation() {
        if (this.data.currentOrder) {
            wx.openLocation({
                latitude: this.data.currentOrder.latitude,
                longitude: this.data.currentOrder.longitude,
                name: this.data.currentOrder.detailAddress,
                address: this.data.currentOrder.detailAddress
            });
        }
    },

    // 拨打客户电话
    callClient(e) {
        const phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    // 开始打卡
    startCheckin(e) {
        this.setData({
            showCheckinModal: true,
            currentOrderId: e.currentTarget.dataset.id,
            checkinPhoto: ''
        });
    },

    // 关闭打卡模态框
    closeCheckinModal() {
        this.setData({
            showCheckinModal: false,
            checkinPhoto: '',
            currentOrderId: null
        });
    },

    // 选择图片
    chooseImage() {
        const that = this;
        wx.chooseMedia({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            mediaType: ['image'],
            maxDuration: 180,
            success(res) {
                const tempFilePath = res.tempFiles[0].tempFilePath;
                // that.setData({ checkinPhoto: tempFilePath });
                that.mockUpload(tempFilePath, 'image')
            }
        });
    },

    // 预览图片
    previewImage() {
        wx.previewImage({
            urls: [this.data.checkinPhoto]
        });
    },

    // 删除图片
    removePhoto() {
        const _this = this;
        _this.Deletefile(_this.data.checkinPhoto).then((res) => {
            if (res.data) {
                this.setData({ checkinPhoto: '' });
            }
        })

    },

    // 图片/视频上传
    mockUpload(filePath, type) {
        const _this = this;
        return new Promise((resolve, reject) => {
            wx.showLoading({
                title: type === 'video' ? '视频上传中...' : '封面上传中...'
            })
            setTimeout(() => {
                let dt1 = new Date();
                let dt2 = util.formatTime5(dt1);
                let params = {
                    tablename: type,
                    tableid: dt2
                }
                wx.uploadFile({
                    url: wx._baseUrl + '/AccountAppService/UploadMedia_myshfw',
                    filePath,
                    header: {
                        'content-type': 'multipart/form-data',
                        'accept': 'application/json'
                    },
                    method: 'POST',
                    // imgType: 1,
                    name: 'Xjd', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
                    formData: params, //HTTP 请求中其他额外的 form data
                    success: function (res) {
                        if (res.statusCode == 200) {
                            let resdata = JSON.parse(res.data);
                            if (type == 'video') {
                                _this.setData({
                                    // [_this.data.medias.video]: resdata.data,
                                    checkinPhoto: resdata.data
                                })
                            } else if (type == 'image') {
                                _this.setData({
                                    // [_this.data.medias.image]: resdata.data,
                                    checkinPhoto: resdata.data
                                })
                            }

                        } else {
                            wx.showToast({
                                title: '上传有误',
                                icon: 'error'
                            })
                        }

                    },
                    fail: err => {

                        wx.showToast({
                            title: '上传失败!',
                        })
                    }
                })
                wx.hideLoading()
                resolve()
            }, 2000)
        })
    },
    // 提交打卡
    submitCheckin() {
        const _this = this;
        const orderId = this.data.currentOrderId;
        if (this.data.checkinPhoto == '') {
            wx.showModal({
                title: '提示',
                content: '请上传图片',
                complete: (res) => {
                    if (res.cancel) {
                        return;
                    }

                    if (res.confirm) {
                        return;
                    }
                }
            })
        }
        this.CheckinServiceOrder(orderId, this.data.checkinPhoto, 'completed').then((res) => {
            _this.loadOrders(_this.data.filterType);

            wx.showToast({

                title: '打卡成功',
                icon: 'success',
                duration: 2000
            });
            _this.setData({
                // orders,
                // filteredOrders: this.filterOrders(orders, this.data.currentStatus),
                showCheckinModal: false,
                checkinPhoto: '',
                currentOrderId: null
            });
        })
        // this.data.orders.map(order => {
        //     if (order.id === orderId) {
        //         return { ...order, status: 'completed' };
        //     }
        //     return order;
        // });

        //     this.setData({
        //         orders,
        //         filteredOrders: this.filterOrders(orders, this.data.currentStatus),
        //         showCheckinModal: false,
        //         checkinPhoto: '',
        //         currentOrderId: null
        //     });

        // wx.showToast({
        //     title: '打卡成功',
        //     icon: 'success',
        //     duration: 2000
        // });
    },
    CancelServiceOrder(param1, param2) {
        return wx.Http.post("/ServiceOrderAPPService/CancelServiceOrder", {
            id: param1,
            Status: param2
        });
    },
    // 取消订单
    cancelOrder(e) {
        const orderId = e.currentTarget.dataset.id;
        const that = this;

        wx.showModal({
            title: '确认取消',
            content: '确定要取消此订单吗？',
            success(res) {
                if (res.confirm) {
                    _this.CancelServiceOrder(orderId, 'cancelled').then((res) => {
                        _this.setData({
                            noMore: false
                        }, () => {
                            _this.loadOrders(_this.data.filterType);
                        })
                    })
                    // const orders = that.data.orders.map(order => {
                    //     if (order.id === orderId) {
                    //         return { ...order, status: 'cancelled' };
                    //     }
                    //     return order;
                    // });

                    // that.setData({
                    //     orders,
                    //     filteredOrders: that.filterOrders(orders, that.data.currentStatus)
                    // });

                    wx.showToast({
                        title: '订单已取消',
                        icon: 'success',
                        duration: 2000
                    });
                }
            }
        });
    },

    // 查看订单详情
    viewOrderDetail(e) {
        const orderId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/packageA/pages/order-detail/index?id=${orderId}`
        });
    },
     // 查看详情
    //  viewDetail(e) {
    //     const orderId = e.currentTarget.dataset.id;
    //     wx.navigateTo({
    //         url: `/packageA/pages/order-detail/index?id=${orderId}`
    //     });
    // },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    //   onReachBottom() {

    //   },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})